package com.wwdx.shiro;

import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import com.wwdx.utils.IpUtils;
import com.wwdx.utils.jackson.JsonUtils;
import org.apache.shiro.web.servlet.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 记录访问日志的过滤器
 * @author liguoliang
 * @date 2018-08-28 16:11:48
 */
public class FireWallFilter extends OncePerRequestFilter {

    /**
     * 白名单
     */
    private List<String> whiteList = new ArrayList<>();

    public void setWhiteList(List<String> whiteList) {
        this.whiteList = whiteList;
    }

    @Override
    protected void doFilterInternal(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        //获取IP地址
        String ipAddr = IpUtils.getIpAddr(request);
        //白名单IP
        if(whiteList.contains(ipAddr)){
            chain.doFilter(req, res);
            return;
        }
        response.setCharacterEncoding(ConstantHolder.Constant.UTF8);
        response.setContentType("application/json;charset=UTF-8");
        ResultBean resultBean = new ResultBean();
        resultBean.setMessage("非白名单IP");
        resultBean.setStatus(ResultBean.FAIL);
        response.getWriter().print(JsonUtils.bean2Json(resultBean));
    }
}